package com.hontech.libratest.activity.fragment.sub

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hontech.libratest.R
import com.hontech.libratest.activity.window.showProg

import com.hontech.libratest.conn.runOta
import com.hontech.libratest.utils.*
import java.io.IOException


class FirmSub (view: View) {

    companion object {
        const val TYPE_MCU = 0
        const val TYPE_APP = 1
    }

    private val btnFirmGet = view.findViewById<Button>(R.id.id_setting_btn_get_firm)
    private val btnAppGet = view.findViewById<Button>(R.id.id_setting_btn_get_app)
    private val rvFirms = view.findViewById<RecyclerView>(R.id.id_setting_rv)
    private val adapter = Adapter()

    init {
        btnFirmGet.onClick(::onClickGetFirm)
        btnAppGet.onClick(::onClickGetApp)
        rvFirms.adapter = adapter
        rvFirms.layoutManager = LinearLayoutManager(view.context, LinearLayoutManager.VERTICAL, false)
    }

    private suspend fun onClickGetFirm() {

        val w = showProg(btnFirmGet, "获取固件信息")

        try {
            val firms = Http.queryMcu()
            adapter.update(firms, TYPE_MCU)
            w.success("获取成功")
        } catch (e: Exception) {
            e.printStackTrace()
            w.error(e.message!!)
        }
    }

    private suspend fun onClickGetApp() {
        val w = showProg(btnFirmGet, "获取App信息")

        try {
            val firms = Http.queryApkFile()
            adapter.update(firms, TYPE_APP)
            w.success("获取成功")
        } catch (e: Exception) {
            e.printStackTrace()
            w.error(e.message!!)
        }
    }

    private class ItemView(view: View) : RecyclerView.ViewHolder(view) {

        private val tvVersion = view.findViewById<TextView>(R.id.id_item_version)
        private val tvDate = view.findViewById<TextView>(R.id.id_item_date)
        private val tvSize = view.findViewById<TextView>(R.id.id_item_size)
        private val tvDescr = view.findViewById<TextView>(R.id.id_item_descr)
        private val btnUpdate = view.findViewById<Button>(R.id.id_item_btn_update)

        private var firm: Http.StoreFile? = null
        private var type = TYPE_MCU

        fun setUp(firm: Http.StoreFile, type: Int) {
            this.firm = firm
            this.type = type
            tvVersion.text = firm.version
            tvDate.text = firm.time()
            tvSize.text = "${firm.size}"
            tvDescr.text = firm.description
            btnUpdate.onClick(::onClickUpdate)
        }

        private suspend fun onInstallApk() {
            val w = showProg(btnUpdate, "开始下载固件")

            try {
                if (!canWriteFile()) {
                    throw IOException("没有文件写入权限")
                }
                val path = Http.doDownloadApk(firm!!.id) {
                    w.show(btnUpdate, "进度:${it}")
                }
                w.success("下载成功")

                installApp(path)
            } catch (e: Exception) {
                e.printStackTrace()
                w.success("下载失败或者没有权限,使用浏览器进行下载")

                val url = "${Http.BASE_URL}/dev_file/get?id=${firm!!.id}"
                startWeb(url)
            }
        }

        private suspend fun onOTA() {
            val w = showProg(btnUpdate, "开始下载固件")
            try {
                val data = Http.doDownloadBin(firm!!.id)

                w.show(btnUpdate, "下载固件成功,开始更新")
                runOta(data) {
                    w.show(btnUpdate, "进度:${it}")
                }
                w.success("更新成功")
            } catch (e: Exception) {
                w.error(e.message!!)
                e.printStackTrace()
            }
        }

        private suspend fun onClickUpdate() {
            if (firm == null) {
                return
            }
            if (type == TYPE_MCU) {
                onOTA()
            } else {
                onInstallApk()
            }
        }
    }

    private class Adapter (var firms: Array<Http.StoreFile> = emptyArray(), var type: Int = TYPE_MCU) : RecyclerView.Adapter<ItemView>() {

        fun update(firms: Array<Http.StoreFile>, type: Int) {
            this.firms = firms
            this.type = type
            notifyDataSetChanged()
        }

        override fun onBindViewHolder(holder: ItemView, position: Int) {
            val firm = firms[position]
            holder.setUp(firm, type)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemView {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_firm, parent, false)
            return ItemView(view)
        }

        override fun getItemCount(): Int {
            return firms.size
        }
    }

}